package com.gl.saasservice.repository;

import com.gl.saasservice.entity.SmartLockAuth;
import com.gl.saasservice.entity.User;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

import java.util.List;


public interface SmartLockAuthRepository extends PagingAndSortingRepository<SmartLockAuth, Long>, JpaSpecificationExecutor<SmartLockAuth> {
    List<SmartLockAuth> findByMobile(String mobile);

    @Modifying
    @Query(value = "update saas_smart_lock_auth m set m.user_name= ?1 ,m.mobile=?2 where m.mobile= ?3",nativeQuery = true)
    public User saveNameAndMobile(String name, String mobile, String oldmobile);

    List<SmartLockAuth> findByLockId(Long lockId);

    List<SmartLockAuth> findByHouseIdAndBindType(String houseId, Integer bindType);

    SmartLockAuth findSmartLockAuthById(Long id);

    @Query("SELECT COUNT(a) FROM SmartLockAuth a WHERE a.lockId = ?1 and a.bindType = 0 AND (a.pwdStatus = 2 OR a.fingerprintStatus = 2 OR a.cardStatus = 2 OR a.cpuStatus = 2 or a.bleStatus = 2)")
    int findSmartLockAuthByLockId(Long lockId);

    @Query("SELECT COUNT(a) FROM SmartLockAuth a WHERE a.lockId = ?1 and a.bindType = 1 AND (a.pwdStatus = 2 OR a.fingerprintStatus = 2 OR a.cardStatus = 2 OR a.cpuStatus = 2 or a.bleStatus = 2)")
    int findPersonSmartLockAuthByLockId(Long lockId);

    List<SmartLockAuth> findByLockIdAndBindType(Long lockId, Integer bindType);

    int deleteByLockId(Long lockId);

    SmartLockAuth findByAuthorUserId(String authorUserId);

    List<SmartLockAuth> findByLockIdIn(List<Long> lockIds);

    @Query("SELECT a FROM SmartLockAuth a WHERE a.houseId = ?1 AND a.matchUserId=?2")
    List<SmartLockAuth> finHouseIdAndMatchUserId(String houseId, String matchUserId);

    List<SmartLockAuth> findByIdIn(List<Long> lockIds);

    @Modifying
    @Query(value = "UPDATE saas_smart_lock_auth SET match_user_id = ?2 WHERE lock_id = ?1 and bind_type = 0", nativeQuery = true)
    int updateMatchUserId(Long lockId, String matchUserId);

    List<SmartLockAuth> findByHouseIdAndBindTypeAndMobile(String houseId, Integer bindType, String mobile);

    @Query(value = "SELECT * FROM saas_smart_lock_auth WHERE (author_user_id = ?1 OR mobile = ?2) AND bind_type = 0", nativeQuery = true)
    List<SmartLockAuth> findOrgLockAuth(String authorUserId, String mobile);

    SmartLockAuth findByCommunityUserId(Long communityUserId);

    @Modifying
    @Query(value = "DELETE FROM saas_smart_lock_auth WHERE lock_id = ?1 AND bind_type = 1", nativeQuery = true)
    void deletePersonAuth(Long lockId);
}
